package com.rzjm.api.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.PutObjectResult;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class OssUtil {

    // endpoint以杭州为例，其它region请按实际情况填写。simple-mall.oss-cn-beijing.aliyuncs.com
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tFMChM8vZoNHi1kX5xs";
    private static final String accessKeySecret = "j9SK49ar6pqAUyW9PegrMDTYtXqIWt";
    private static final String bucketName = "yuedou";


    public static final int TYPE_USER_PHOTOS = 0;//用户头像
    public static final int TYPE_PRODUCT_PHOTOS = 1;//商品的图片
    public static final int TYPE_TITLEMENU_PHOTOS = 2;//菜单
    public static final int TYPE_SECTION_PHOTOS = 3;//内容行
    public static final int TYPE_MATERIAL_PHOTOS = 4;//素材库
    public static final int TYPE_ADVERT_PHOTOS = 5;//广告
    public static final int TYPE_LUNBO_PHOTOS = 6;//轮播
    public static final int TYPE_ESTATE_PHOTOS = 7;//小区二维码
    public static final int TYPE_SHOP_PHOTOS = 8;//商家LOGO
    public static final int TYPE_PLATFORM_HELP_PHOTOS = 9;//帮助文档
    public static final int TYPE_DEVICE_PHOTOS = 10;//帮助文档
    public static final int TYPE_APP_FILE = 11;//帮助文档
    public static final int TYPE_PRODUCT_QRCODE = 12;//帮助文档
    public static final int TYPE_COUPONS = 13;//优惠券
    public static final int TYPE_TERMINALS = 14;//优惠券
    public static final int TYPE_CHARGER = 15;//充电设备
    public static final int TYPE_RECEIPT = 16;//收据
    public static final int TYPE_SET_MEAL = 17;//套餐活动
    public static final int TYPE_PROMOTER_MEAL = 18;//推广元
    public static final int TYPE_CAR_MEAL = 19;//名车
    public static final int TYPE_ADOPT_MEAL = 20;//领养
    public static final int TYPE_PROMTION_QR_CODE_URL=21;//直播间
    public static final int TYPE_VIDEO_URL=22;
    public static final int TYPE_VIDEO_MASK_URL=23;
    public static final int TYPE_ORDER_WARM_HEART_GROUP = 24;//团购活动图片
    public static final int TYPE_WMJ = 25;//微门禁
    public static final int TYPE_MER_TABLE = 26;//餐桌
    public static final int TYPE_MER_VIP = 27;//会员
    public static final int TYPE_PRODUCT_ORDER = 28;//订单支付二维码

    public static final int TYPE_ELECTRIC_METER = 29;//电表二维码


    public static final int TYPE_DEVICE_WATER_QR = 33; //水机二维码


    public static final String USER_IMG_PREFIX  = "user/";
    public static final String PRODUCT_IMG_PREFIX  = "product/";
    public static final String TITLEMENU_IMG_PREFIX  = "titlemenu/";
    public static final String SECTION_IMG_PREFIX  = "section/";
    public static final String MATERIAL_IMG_PREFIX  = "material/";
    public static final String ADVERT_IMG_PREFIX  = "advert/";
    public static final String LUNBO_IMG_PREFIX  = "lunbo/";
    public static final String ESTATE_IMG_PREFIX  = "estate/";
    public static final String SHOP_IMG_PREFIX  = "shop/";
    public static final String PLATFORM_HELP_IMG_PREFIX  = "help/";
    public static final String DEVICE_IMG_PREFIX  = "device/";
    public static final String APP_FILE_PREFIX  = "appversion/";
    public static final String PRODUCT_QRCODE_PREFIX  = "product_qr/";
    public static final String COUPONS_PREFIX  = "coupons/";
    public static final String TERMINALS_PREFIX  = "terminals/";
    public static final String CHARGER_PREFIX  = "charger/";
    public static final String RECEIPT_PREFIX  = "receipt/";
    public static final String SET_MEAL_PREFIX  = "set_meal/";
    public static final String PROMOTER_PREFIX  = "promoter/";
    public static final String CAR_PREFIX  = "car/";
    public static final String ADOPT_PREFIX  = "adopt/";
    public static final String PROMTION_QR_CODE_URL="liveRoom/";
    public static final String VIDEO_URL="video/";
    public static final String VIDEO_MASK_URL="videoMask/";
    public static final String ORDER_WARM_HEART_IMG_PREFIX = "order_warm/";
    public static final String WMJ_IMG_PREFIX = "wmj/";
    public static final String MER_TABLE = "mer_table/";
    public static final String MER_VIP = "mer_vip/";
    public static final String PRODUCT_ORDER_PREFIX = "product_order/";
    public static final String ELECTRIC_METER_PREFIX = "electric_meter/";
    public static final String WATER_DEVICE_QR = "water_device_qr/";


    private static final int validity = 60 * 1000;


    public static void main(String[] args){
        String url = "/article/1/2c1157af-7612-43bd-b34c-e928338ab6a9.png";
        url = url.substring(1);
        boolean bl = deleteObjByKey(url);
        if(bl){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }



    /**
     * 获取  上传图片的 路径前缀
     * @param upload_type
     * @return
     */
    public static String getUploadPrefix(int upload_type){
        String prefix = null;
        switch (upload_type) {
            case TYPE_USER_PHOTOS:
                prefix = USER_IMG_PREFIX;
                break;
            case TYPE_PRODUCT_PHOTOS:
                prefix = PRODUCT_IMG_PREFIX;
                break;
            case TYPE_TITLEMENU_PHOTOS:
                prefix = TITLEMENU_IMG_PREFIX;
                break;
            case TYPE_SECTION_PHOTOS:
                prefix = SECTION_IMG_PREFIX;
                break;
            case TYPE_MATERIAL_PHOTOS:
                prefix = MATERIAL_IMG_PREFIX;
                break;
            case TYPE_ADVERT_PHOTOS:
                prefix = ADVERT_IMG_PREFIX;
                break;
            case TYPE_LUNBO_PHOTOS:
                prefix = LUNBO_IMG_PREFIX;
                break;
            case TYPE_ESTATE_PHOTOS:
                prefix = ESTATE_IMG_PREFIX;
                break;
            case TYPE_SHOP_PHOTOS:
                prefix = SHOP_IMG_PREFIX;
                break;
            case TYPE_PLATFORM_HELP_PHOTOS:
                prefix = PLATFORM_HELP_IMG_PREFIX;
                break;
            case TYPE_DEVICE_PHOTOS:
                prefix = DEVICE_IMG_PREFIX;
                break;
            case TYPE_APP_FILE:
                prefix = APP_FILE_PREFIX;
                break;
            case TYPE_PRODUCT_QRCODE:
                prefix = PRODUCT_QRCODE_PREFIX;
                break;
            case TYPE_COUPONS:
                prefix = COUPONS_PREFIX;
                break;
            case TYPE_TERMINALS:
                prefix = TERMINALS_PREFIX;
                break;
            case TYPE_CHARGER:
                prefix = CHARGER_PREFIX;
                break;
            case TYPE_RECEIPT:
                prefix = RECEIPT_PREFIX;
                break;
            case TYPE_SET_MEAL:
                prefix = SET_MEAL_PREFIX;
                break;
            case TYPE_PROMOTER_MEAL:
                prefix = PROMOTER_PREFIX;
                break;
            case TYPE_CAR_MEAL:
                prefix = CAR_PREFIX;
                break;
            case TYPE_ADOPT_MEAL:
                prefix = ADOPT_PREFIX;
                break;
            case TYPE_PROMTION_QR_CODE_URL:
                prefix=PROMTION_QR_CODE_URL;
                break;
            case TYPE_VIDEO_MASK_URL:
                prefix=VIDEO_MASK_URL;
                break;
            case TYPE_VIDEO_URL:
                prefix=VIDEO_URL;
                break;
            case TYPE_ORDER_WARM_HEART_GROUP:
                prefix = ORDER_WARM_HEART_IMG_PREFIX;
                break;
            case TYPE_WMJ:
                prefix = WMJ_IMG_PREFIX;
                break;
            case TYPE_MER_TABLE:
                prefix = MER_TABLE;
                break;
            case TYPE_MER_VIP:
                prefix = MER_VIP;
                break;
            case TYPE_PRODUCT_ORDER:
                prefix = PRODUCT_ORDER_PREFIX;
                break;
            case TYPE_ELECTRIC_METER:
                prefix = ELECTRIC_METER_PREFIX;
                break;
            case TYPE_DEVICE_WATER_QR:
                prefix = WATER_DEVICE_QR;
                break;
        }
        return prefix;
    }


    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     * @param upload_type 要上传的文件类型
     */
    public static boolean upload(InputStream inputStream,String fileName,int upload_type) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
			OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
            String prefix = getUploadPrefix(upload_type);
			System.out.println("文件路径：" + prefix + fileName);
            if (prefix!=null){
				try{
					PutObjectResult putObjectResult = ossClient.putObject(bucketName, prefix + fileName, inputStream);
					String eTag = putObjectResult.getETag();
					System.out.println("upload " + prefix + fileName +"-->"+ eTag);

				} catch (OSSException oe) {
					System.out.println("Caught an OSSException, which means your request made it to OSS, "
						+ "but was rejected with an error response for some reason.");
					System.out.println("Error Message:" + oe.getErrorMessage());
					System.out.println("Error Code:" + oe.getErrorCode());
					System.out.println("Request ID:" + oe.getRequestId());
					System.out.println("Host ID:" + oe.getHostId());
				} catch (ClientException ce) {
					System.out.println("Caught an ClientException, which means the client encountered "
						+ "a serious internal problem while trying to communicate with OSS, "
						+ "such as not being able to access the network.");
					System.out.println("Error Message:" + ce.getMessage());
				}
            }
            // 关闭client。
            ossClient.shutdown();
			System.out.println("upload "+ prefix + fileName +"是否成功-->"+ (ret?"YES":"NO"));
        }
        return ret;
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     */
    public static boolean upload(InputStream inputStream,String fileName) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
//            String prefix = getUploadPrefix(upload_type);
            if (fileName!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }

    /**
     * 根据key获取url
     * @param object_key
     * @return
     */
    public static String getSignUrl(String object_key){
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        //validity url的有效期
        URL url = ossClient.generatePresignedUrl(bucketName, object_key, new Date(new Date().getTime()+validity));
		//关闭client
        ossClient.shutdown();
        return url==null?null:url.toString();
    }


    /**
     * 删除文件
     * @param objKey
     * @return
     */
    public static boolean deleteObjByKey(String objKey) {
        boolean ret = false;
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.deleteObject(bucketName,objKey);
        // Object是否存在。
        ret = ossClient.doesObjectExist(bucketName, objKey);
        ossClient.shutdown();
        return !ret;
    }

    public static BufferedImage getImageInfoByUrl(String urlStr){

        try{
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            int length = urlConnection.getContentLength();
            System.out.print("length: " + length);
            if(length == -1){
                System.out.print("image not exist");
            }else{
                BufferedImage sourceImg = ImageIO.read(url);
                System.out.print("image width:" + sourceImg.getWidth());
                System.out.print("image height:" + sourceImg.getHeight());
                return sourceImg;
            }
        }catch (MalformedURLException e){
//            logger.info("url not right " + e.getMessage(), e);
        } catch (IOException e){
//            logger.info("IOException " + e.getMessage(), e);
        }
        return null;
    }
}
